package com.tanhua.dubbo.es.api;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.UserLocation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.geo.GeoPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;

import javax.annotation.PostConstruct;

/**
 * @author 小霞
 * @version 1.0
 * @description: 搜索附近
 * @date 2021/7/10 20:57
 */
@Service(version = "1.0.0")
@Slf4j
public class UserLocationApiImpl implements UserLocationApi {


    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 初始化索引库
     */
    @PostConstruct
    public void initIndex() {
        //判断索引库是否存在，如果不存在，需要创建
        if (!this.elasticsearchTemplate.indexExists("tanhua")) {
            this.elasticsearchTemplate.createIndex(UserLocation.class);
        }

        //判断表是否存在，如果不存在，需要创建
        if (!this.elasticsearchTemplate.typeExists("tanhua", "user_location")) {
            this.elasticsearchTemplate.putMapping(UserLocation.class);
        }

    }

    @Override
    public Boolean updateUserLocation(Long userId, Double longitude, Double latitude, String address) {
        //查询个人的地理位置数据，如果不存在，需要新增，如果是存在数据，更新数据

        GetQuery getQuery = new GetQuery();
        //设置查询条件
        getQuery.setId(String.valueOf(userId));
        UserLocation userLocation = this.elasticsearchTemplate.queryForObject(getQuery, UserLocation.class);

        //判断对象里是否有值
        if (ObjectUtil.isEmpty(userLocation)) {
            //没有直接就直接新增数据
            userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(userLocation.getCreated());
            userLocation.setLastUpdated(userLocation.getCreated());
            //设置地理位置,设置经纬度
            userLocation.setLocation(new GeoPoint(latitude,longitude));

            //保存数据
            IndexQuery indexQuery = new IndexQueryBuilder().withObject(userLocation).build();
            this.elasticsearchTemplate.index(indexQuery);
        }else {

        }
        return null;
    }
}
